package scenic;

import java.awt.Rectangle;

import scenic.geom.Affine2;
import scenic.jni.Renderer;

/**
 * <p>This scene node clips its children inside a clip area. The clip
 * area is defined by a scene. The clipping is performed by modulating
 * the child scene with the clip scene. The clip scene is usually a 
 * shape, but it can be any scene.</p>
 * 
 * <p>SceneClip can be used to paint a shape with a brush by setting
 * the shape as the clip shape and adding the brush as a child.</p>
 *
 */
public class SceneClip extends SceneContainer {
	private SceneNode clip;

	/**
	 * Construct an SceneClip object with the given clip scene.
	 * 
	 * @param clip the clip scene.
	 */
	public SceneClip(SceneNode clip) {
		clip.close();
		this.clip = clip;
		clip.parent = this;
	}

	/**
	 * Gets the clip scene.
	 * 
	 * @return the clip scene.
	 */
	public SceneNode getClip() {
		return clip;
	}

	/**
	 * Sets the clip scene.
	 * 
	 * @param clip the clip scene.
	 */
	public void setClip(SceneNode clip) {
		clip.close();
		this.clip.parent = null;
		this.clip = clip;
		clip.parent = this;
		changed();
	}
	
	public void remove(SceneNode node) {
		if(node == clip) {
			clip = null;
			node.parent = null;
			changed();
		} else {
			super.remove(node);
		}
	}
	
	void draw(DrawContext context, Affine2 transform, Rectangle visibleArea) {
		Rectangle bounds = getBounds(transform);
			
		if(bounds.width <= 0 || bounds.height <= 0)
			return;
		bounds = addSafeMargin(bounds);
		context.renderer.beginSurface(context.context, bounds, Renderer.SURFACE_TYPE_COLOR);
		super.draw(context, transform, bounds);
		context.renderer.beginSurface(context.context, bounds, Renderer.SURFACE_TYPE_COLOR);
		clip.draw(context, transform, bounds);
		context.renderer.color(context.context, 1.0f, 1.0f, 1.0f, 1.0f);
		context.renderer.drawSurfaceAndClip(context.context);
	}
	
	protected void setVisibility(boolean state) {
		if(clip != null)
			clip.setVisibility(state);
		super.setVisibility(state);
	}
	
	Rectangle getBounds(Affine2 transform) {
		Rectangle result = super.getBounds(transform);

		Util.common(result, clip.getBounds(transform));
		return result;
	}
	
}
